package priv.pront.code.lanqiao.competition.course.date0331;

import java.util.Scanner;


public class 蓝桥杯_2022_国A_环境治理 {

    static int n; //城市的个数
    static int q;// 期望达到的P指标
    static long left = 0,right = 1000000000;
    static long[][] startDis, lowest,curDis;

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        n = scanner.nextInt();
        q = scanner.nextInt();
        startDis = new long[n][n];
        lowest = new long[n][n];
        curDis = new long[n][n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                startDis[i][j] = scanner.nextInt();
            }
        }

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                lowest[i][j] = scanner.nextInt();
                curDis[i][j] = lowest[i][j];
            }
        }

        if(floyd() < q){
            System.out.println(-1);
            return;
        }

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                curDis[i][j] = startDis[i][j];
            }
        }
        if(floyd() <= q){
            System.out.println(0);
            return;
        }

        while (left < right) {
            long mid = left + (right - left) / 2;
            if(check(mid)){
                right = mid;
            }else{
                left = mid + 1;
            }
        }
        System.out.println(right);
    }

    private static boolean check(long mid) {
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                curDis[i][j] = startDis[i][j];
            }
        }
        long cycle = mid / n;
        long s  = mid  % n;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if(i == j) continue;
                if(i < s){
                    curDis[i][j] = Math.max(lowest[i][j], curDis[i][j] - cycle - 1);
                }else{
                    curDis[i][j] = Math.max(lowest[i][j], curDis[i][j] - cycle);
                }
                curDis[j][i] = curDis[i][j];
            }
        }
        return floyd() <= q;

    }

    private static long floyd() {
        long ans = 0;
        //        K 个中继节点
        for (int k = 0; k < n; k++) {
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    curDis[i][j] = Math.min(curDis[i][j], curDis[i][k] + curDis[k][j]);
                }
            }
        }
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                ans += curDis[i][j];
            }
        }
        return ans;
    }
}
